<template>
  <div class="btn-group">
    <button
      :class="{ 'btn-disabled': currentPage <= 1 }"
      class="btn"
      @click="btnClicked(currentPage - 1)"
    >
      上一页
    </button>
    <button
      v-for="i in list"
      :class="{ 'btn-active': i === currentPage }"
      class="btn"
      @click="btnClicked(i)"
    >
      {{ i }}
    </button>
    <button
      :class="{ 'btn-disabled': currentPage >= pageItemCount }"
      class="btn"
      @click="btnClicked(currentPage + 1)"
    >
      下一页
    </button>
  </div>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  name: 'Pagination',
  emits: ['update:currentPage'],
  props: {
    totalCount: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      default: 10
    },
    currentPage: {
      type: Number,
      default: 1
    }
  },

  setup: (props, { emit }) => {
    const totalCount = ref(props.totalCount)
    const list = ref([])
    const pageItemCount = ref(0)

    const update = () => {
      pageItemCount.value = Math.ceil(props.totalCount / props.pageSize)
      list.value = [1, '...', 0, '...', pageItemCount.value]

      if (props.currentPage !== 1 && props.currentPage !== pageItemCount.value) {
        list.value[2] = props.currentPage
        if (props.currentPage - 1 === 1) {
          list.value.splice(1, 1)
        }

        if (props.currentPage + 1 === pageItemCount.value) {
          list.value.splice(list.value.length - 2, 1)
        }
      }

      if (props.currentPage === 1 || props.currentPage >= pageItemCount.value) {
        list.value = [1, '...', pageItemCount.value]
      }

      if (pageItemCount.value <= 1 || totalCount <= 0) {
        list.value = [1]
      }

      if (pageItemCount.value === 2) {
        list.value.splice(1, 1)
      }
    }

    const btnClicked = async (id) => {
      if (id !== '...') {
        await emit('update:currentPage', id)
        update()
      }
    }

    watch(
      () => props.totalCount,
      (count) => {
        totalCount.value = count
        update()
      }
    )

    return {
      totalCount,
      btnClicked,
      list,
      pageItemCount
    }
  }
}
</script>

<style scoped></style>
